import { Component, OnInit } from '@angular/core'
import { Router, ActivatedRoute, Params } from '@angular/router'
import { HttpClientService } from 'src/app/common/httpClient/http'
import { HomeService } from './services/home.service'
import { ZoneService } from 'src/app/common/services/zone.service'
import { CommonUtil } from 'src/app/common/utils/common.util'
import { CoolLocalStorage } from 'src/app/common/coolStorage/cool-local-storage'
import { CoolSessionStorage } from 'src/app/common/coolStorage/cool-session-storage'

@Component({
  selector: 'app-index',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.scss']
})
export class IndexComponent implements OnInit {
  // 当前城市
  city: any
  // 图标入口
  iconbar = [
    { name: '全部楼盘', icon: 'all' },
    { name: '在售楼盘', icon: 'sale' },
    { name: '优选楼盘', icon: 'better' },
    { name: '最近开盘', icon: 'last' }
  ]
  // 压屏窗
  Notice = {
    show: false,
    img: '',
    url: ''
  }
  // 轮播图
  Poster = []
  // 房市行情
  Quotation: any = {
    show: false,
    average: 0,
    deal: 0
  }
  // 推荐活动
  activity = []
  // 推荐楼盘
  estates = []
  // 加载失败
  error = false
  // 加载中
  loading = false
  // 是否存在更多楼盘
  nomore = false

  constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private homeService: HomeService,
    private zoneService: ZoneService,
    private utils: CommonUtil,
    private http: HttpClientService,
    private storage: CoolLocalStorage,
    private session: CoolSessionStorage
  ) {
    window.onscroll = e => {
      let clientHeight = document.documentElement.clientHeight
      let scrollTop = document.documentElement.scrollTop || document.body.scrollTop
      let scrollHeight = document.body.scrollHeight
      // 触底了
      if (scrollTop + clientHeight === scrollHeight) {
        let isHome = router.url.indexOf('/workspace/home/index') > -1
        if (!this.nomore && isHome) {
          this.getList()
        }
      }
    }
  }

  // 初始化
  ngOnInit() {
    let location: any = this.storage.getObject('location')
    this.loading = true
    this.homeService.reqdata.pager.Start = 10
    this.activatedRoute.params.subscribe((params: Params) => {
      // 如果参数内有城市信息，那么是从选择城市页面过来
      // 如果本地存储有定位，那么就拿本地存储里的城市信息去请求数据
      // 如果本地存储没有定位，那么就拿南昌去请求数据
      if (params.Id) {
        console.log('从切换城市页面进入，参数是：' + JSON.stringify(params))
        this.getCityInList(params.Name)
      } else if (location) {
        console.log('本地已有经纬度，数值是：' + JSON.stringify(location))
        this.getCityInList(location.city)
      } else {
        console.log('本地没有经纬度，取默认城市南昌')
        this.getCityInList('南昌市')
      }
    })
  }
  // 设置城市数据
  setCityData(city) {
    // 1. 设置基本信息
    this.city = { Id: city.Id, Name: city.Name }
    this.storage.setItem('zone', city.Id)
    // 2. 设置配置信息
    this.getConfig(city)
    // 3. 设置列表信息
    this.getDetail(city.Id)
  }
  // 设置配置信息
  getConfig(city) {
    let config: any = JSON.parse(city.Config)
    let view = (config.Chart && config.Chart.MonthChartView) || null
    // 弹窗
    let Notice = config.Notice || ''
    let noticeShowTime = this.session.getItem('noticeShowTime')
    // 轮播图
    let Poster = config.Poster || []
    // 房市行情-是否展示、均价和交易量
    let show = (config && config['MarketEnable']) || false
    let average = 0
    let deal = 0
    // 楼盘列表内的筛选数据源(区域和地铁)
    let regionUrl, metroUrl

    // 弹窗
    this.Notice.img = this.utils.getThumbnail(Notice.Photo)
    this.Notice.url = Notice.Url
    if (Notice && !noticeShowTime) {
      this.Notice.show = true
      this.session.setItem('noticeShowTime', '1')
    }

    // 轮播图
    Poster.map(item => {
      let Photo = this.utils.getThumbnail(item.Photo)
      item.Photo = Photo
      return item
    })
    this.Poster = Poster
    // 房市行情
    if (view) {
      average = view.Items[view.Items.length - 1].Value * 10000 || 0
      deal = config.Chart.MonthChartView.Compare.Count || 0
    }
    this.Quotation = { show: show, average: average, deal: deal }

    // 楼盘列表内的筛选数据源(区域和地铁)
    if (config.Profile && config.Profile.length > 0) {
      for (let i = 0; i < config.Profile.length; i++) {
        if (config.Profile[i].Name === 'Region') {
          regionUrl = config.Profile[i].Url
        } else if (config.Profile[i].Name === 'Metro') {
          metroUrl = config.Profile[i].Url
        }
      }
      this.getAreaData(regionUrl, metroUrl)
    }

    this.storage.setObject('config', config)
  }
  // 获取城市详情
  getDetail(cityId) {
    let reqdata = { zone: cityId }
    this.zoneService.fetch(
      reqdata,
      res => {
        this.loading = false
        if (res.Success && res.Result) {
          // 楼盘数据过滤
          this.estates = res.Result.ProjectSummarys.map(item => {
            let Photo = this.utils.getThumbnail(item.Photo)
            let Tag = this.utils.getTag(item.Tag)
            item.Photo = Photo
            item.Tag = Tag
            if (item.Landmark && item.Landmark.indexOf('[') > -1) {
              item.Landmark = JSON.parse(item.Landmark)[0]
            }
            return item
          })
          // 活动数据过滤
          this.activity = res.Result.PromotionSummarys.map(item => {
            let Photo = this.utils.getThumbnail(item.Photo)
            let obj = { Id: item.Id, Photo: Photo, Title: item.Title, Project: item.Project }
            return obj
          })
        }
      },
      () => {
        this.loading = false
      }
    )
  }
  // 根据城市名从列表中匹配
  getCityInList(cityName) {
    let flag = false
    let target: any
    let temp: any
    this.getCityList(res => {
      for (let i = 0; i < res.length; i++) {
        if (cityName.indexOf(res[i].Name) > -1) {
          flag = true
          temp = res[i]
        }
      }
      // 如果传入的城市在列表中有，那么取该城市
      // 否则取第一个
      if (flag) {
        target = temp
      } else {
        target = res[0]
      }
      this.setCityData(target)
    })
  }
  // 获取城市列表
  getCityList(callback) {
    let cityList: any = this.storage.getObject('cityList')
    if (cityList && cityList.length > 0) {
      callback(cityList)
    } else {
      this.zoneService.query(res => {
        if (res.Success && res.Result) {
          this.storage.setObject('cityList', res.Result.Value)
          callback(res.Result.Value)
        }
      })
    }
  }
  // 轮播图跳转
  navigateTo(url) {
    let result = this.utils.getNivigateLink(url)
    if (!result) {
      return false
    } else {
      this.router.navigateByUrl(result)
    }
  }
  // 获取更多推荐楼盘
  getList() {
    this.homeService.getEstateList(res => {
      if (res.Success && res.Result) {
        // 下一次的起始条目需要加上本次请求到的数据条数
        this.homeService.reqdata.pager.Start += res.Result.Value.length
        // 如果本次请求到的数据小于每页总数，说明没有下一页了
        if (res.Result.Value.length < this.homeService.reqdata.pager.Limit) {
          this.nomore = true
        } else {
          this.nomore = false
        }
        // 数据处理
        let data = res.Result.Value.map(item => {
          item.Photo = this.utils.getThumbnail(item.Photo)
          if (item.Landmark) {
            item.Landmark = JSON.parse(item.Landmark)[0]
          }
          if (item.Tag) {
            let Tag = JSON.parse(item.Tag)
            if (Tag.length > 3) {
              Tag.length = 3
            }
            item.Tag = Tag
          }
          return item
        })
        this.estates = this.estates.concat(data)
      } else {
        this.nomore = false
      }
    })
  }
  // 列表性能优化
  trackByFn(index, item) {
    return item.Id
  }
  // 获取楼盘列表内的筛选数据源(区域和地铁)
  getAreaData(a, b) {
    this.http.post({}, a, res1 => {
      this.storage.setObject('region', res1)
    })
    this.http.post({}, b, res2 => {
      this.storage.setObject('metro', res2)
    })
  }
}
